package com.nine.news.util;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.OSSObjectSummary;
import com.aliyun.oss.model.ObjectListing;

import javax.imageio.stream.FileImageInputStream;
import java.io.*;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * @Author: szhan
 * @Date: 2023/03/15/8:12 PM
 * @Description:
 */
public class AliOssUtil {
    private static final String endpoint ;
    private static final String accessKeyId ;
    private static final String accessKeySecret;
    private static final OSS client;
    private static final String bucketName;

    static {
        endpoint = "oss-cn-beijing.aliyuncs.com";
        accessKeyId = "LTAI5tRzcggU3JUhcWkj79uX";
        accessKeySecret = "xlcT2GqdVCcfHlRCJgdfiNXkCMufuu";
        bucketName = "project-9";
        client = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
    }

    /**
     * 创建存储空间*/
    public static void createBucket(String bucketName) {
        client.createBucket(bucketName);
    }

    /**
     * 上传文件
     * @param objName 对象名，文件名 要求唯一
     * @param url 图片的url*/
    public static void loadFile(String objName,String url) {
        client.putObject(bucketName, objName, new ByteArrayInputStream(image2byte(url)));
    }

    /**
     * 获取访问名称
     * @param objName 对象名
     * @param year 访问链接的有效器*/
    public static String getPath(String objName,int year){
        Calendar calendar=Calendar.getInstance();
        calendar.add(Calendar.YEAR,year);
        return client.generatePresignedUrl(bucketName,objName,calendar.getTime()).toString();
    }
    /**
     * 获取存储空间中的对象名*/
    public static List<String> getFileList(){
        ObjectListing listing=client.listObjects(bucketName);
        List<String> names=new ArrayList<>();
        for (OSSObjectSummary objectSummary : listing.getObjectSummaries()) {
            names.add(objectSummary.getKey());
        }
        return names;
    }
    /**
     * 删除文件
     * @param objname 对象名*/
    public static void delFile(String objname){
        client.deleteObject(bucketName,objname);
    }

    /**
     *图片到byte数组*/
    private static byte[] image2byte(String path){
        byte[] data = null;
        FileImageInputStream input = null;
        try {
            input = new FileImageInputStream(new File(path));
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            byte[] buf = new byte[1024];
            int numBytesRead = 0;
            while ((numBytesRead = input.read(buf)) != -1) {
                output.write(buf, 0, numBytesRead);
            }
            data = output.toByteArray();
            output.close();
            input.close();
        }
        catch (FileNotFoundException ex1) {
            ex1.printStackTrace();
        }
        catch (IOException ex1) {
            ex1.printStackTrace();
        }
        return data;
    }


}
